package cn.jtfadmin.base.filesystem.annos.handle;


import cn.jtfadmin.base.filesystem.config.FileSystem;
import cn.jtfadmin.base.lang.config.ApplicationHolder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * url序列化 请查看jackson
 */
public class FileSerializer extends StdSerializer<String> implements ContextualSerializer {


    /**
     *
     */
    private static final long serialVersionUID = 1L;


    private String fileSuffix = "_fileUrl";

    private static FileSerializer distance = new FileSerializer();

    public FileSerializer() {
        super(String.class);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        return distance;
    }


    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (!StringUtils.hasText(value)) {
            gen.writeNull();
            return;
        }
        gen.writeString(value);
        FileSystem fileSystemConfig = ApplicationHolder.getApplicationContext().getBean(FileSystem.class);


        String currentName = gen.getOutputContext().getCurrentName();

        String[] values = StringUtils.delimitedListToStringArray(value, ",");
        List<String> valueList = new ArrayList<>(values.length);
        for (String s : values) {
            valueList.add(fileSystemConfig.getFileVisitHttpUrl(s));
        }
        gen.writeStringField(currentName + fileSuffix, StringUtils.collectionToCommaDelimitedString(valueList));
        return;

    }


}
